package com.ruoyi.labdata.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.support.logging.LogFactory;
import com.ruoyi.college.service.ILabOrgKindRelRolesService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.labdata.domain.LabEmployee;
import com.ruoyi.labdata.domain.LabEmployeeInfoDto;
import com.ruoyi.labdata.domain.LabHoliday;
import com.ruoyi.labdata.domain.LabReservation;
import com.ruoyi.labdata.domain.LabReservationParameterPersonnel;
import com.ruoyi.labdata.service.ILabEmployeeRoleService;
import com.ruoyi.labdata.service.ILabEmployeeService;
import com.ruoyi.labdata.service.ILabHolidayService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.utils.NyMessageSendUtil;

/**
 * 实验室工作人员Controller
 * 
 * @author winner pan
 * @date 2022-02-02
 */
@RestController
@RequestMapping("/labdata/employee")
public class LabEmployeeController extends BaseController {
	private static final String USER_VERIFY = "User_verify_";

	@Autowired
	private ILabEmployeeService labEmployeeService;

	@Autowired
	private ILabOrgKindRelRolesService orgKindRelRolesService;
	@Autowired
    private ISysDeptService deptService;
	//@Autowired
	//private ISysRoleService roleService;
	
	@Autowired
	private ILabEmployeeRoleService labEmployeeRoleService;

	//@Autowired
	//private ISysPostService postService;

	@Autowired
	private ISysUserService userService;
	
	@Autowired
    private RedisCache redisCache;
	
	@Autowired
	private ILabHolidayService labHolidayService;
	
	private static final Logger log =LoggerFactory.getLogger(LabEmployeeController.class);

	/**
	 * 查询实验室工作人员列表
	 */
	@PreAuthorize("@ss.hasPermi('labdata:employee:query')")
	@GetMapping("/list")
	public TableDataInfo list(LabEmployee labEmployee) {
		startPage();
		List<LabEmployee> list = labEmployeeService.selectLabEmployeeList(labEmployee);
		return getDataTable(list);
	}

	//@PreAuthorize("@ss.hasPermi('labdata:employee:query')")
	/**
	 * 公共组件查询用户信息使用,不加权限
	 * */
	@GetMapping("/query")
	public TableDataInfo query(LabEmployee labEmployee) {
		startPage();
		List<LabEmployee> list = labEmployeeService.chooseUsersQuery(labEmployee);
		return getDataTable(list);
	}
	
	//@PreAuthorize("@ss.hasPermi('labdata:employee:query')")
	/**
	 * 公共组件查询员工信息使用,不加权限
	 * */
	@GetMapping("/queryEmployee")
	public TableDataInfo queryEmployee(LabEmployee labEmployee) {
		startPage();
		if(labEmployee.getCheckOrgList()!=null){
			String[] orgIdStrArray = labEmployee.getCheckOrgList();
			List<SysDept> deptList = deptService.selectSysDeptByIds(orgIdStrArray);
			StringBuffer ancestorsBuffer = new StringBuffer();
			for(SysDept dept : deptList){
				ancestorsBuffer.append(dept.getAncestors());
			}
			labEmployee.setCheckedOrgIds(ancestorsBuffer.toString());
		}
		List<LabEmployee> list = labEmployeeService.chooseEmployeeQuery(labEmployee);
		return getDataTable(list);
	}

	@GetMapping("/getCheckedList")
	public AjaxResult getCheckedList(LabEmployee labEmployee) {
		List<LabEmployee> list = labEmployeeService.chooseUsersQuery(labEmployee);
		return AjaxResult.success(list);
	}
	/**
	 * 实验室工作人员身份验证
	 */
	@Log(title = "工作人员验证码发送", businessType = BusinessType.GRANT)
	@GetMapping("/sendCode/{employeeNo}")
	public AjaxResult sendverifyCode(@PathVariable String employeeNo) {
		String sources = "0123456789";
		Random rand = new Random();
		StringBuffer flag = new StringBuffer();
		for (int j = 0; j < 6; j++){
			flag.append(sources.charAt(rand.nextInt(9)) + "");
		}
		if(!log.isDebugEnabled()){
			NyMessageSendUtil.sendMsg("身份验证消息", "验证码:"+flag.toString()+" 实验室综合管理系统接收到身份验证请求，请妥善保管好该验证码，如果确认不是本人操作请忽略.", NyMessageSendUtil.MsgType_UC_UX, "("+employeeNo+")");
		}
		redisCache.setCacheObject(USER_VERIFY+employeeNo, flag.toString(), Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
		return toAjax(1);
	}
	/**
	 * 实验室工作人员身份验证
	 */
	@Log(title = "工作人员验证", businessType = BusinessType.GRANT)
	@GetMapping("/verifyCode/{employeeNo}/{code}")
	public AjaxResult verifyCode(@PathVariable String employeeNo, @PathVariable String code) {
		String verifyCode = redisCache.getCacheObject(USER_VERIFY+employeeNo);
		if(log.isDebugEnabled() || (verifyCode!=null && verifyCode.equals(code))){
			return AjaxResult.success("1");
		}else{
			return AjaxResult.success("0");
		}
	}
	
	/**
	 * 实验室工作人员身份验证
	 */
	@Log(title = "工作人员验证", businessType = BusinessType.GRANT)
	@GetMapping("/verify/{employeeNo}")
	public AjaxResult verifyEmployee(@PathVariable String employeeNo) {
		String sources = "0123456789";
		Random rand = new Random();
		StringBuffer flag = new StringBuffer();
		for (int j = 0; j < 6; j++){
			flag.append(sources.charAt(rand.nextInt(9)) + "");
		}
		NyMessageSendUtil.sendMsg("身份验证消息", "验证码:"+flag.toString()+" 实验室综合管理系统接收到身份验证请求，请妥善保管好该验证码，如果确认不是本人操作请忽略.", NyMessageSendUtil.MsgType_UC_UX, "("+employeeNo+")");
		redisCache.setCacheObject(USER_VERIFY+employeeNo, flag.toString(), Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
		return toAjax(1);
	}

	/**
	 * 导出实验室工作人员列表
	 */
	//@PreAuthorize("@ss.hasPermi('labdata:employee:export')")
	/*@Log(title = "实验室工作人员", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult export(LabEmployee labEmployee) {
		List<LabEmployee> list = labEmployeeService.selectLabEmployeeList(labEmployee);
		ExcelUtil<LabEmployee> util = new ExcelUtil<LabEmployee>(LabEmployee.class);
		return util.exportExcel(list, "employee");
	}*/

	/**
	 * 获取实验室工作人员详细信息
	 */
	@PreAuthorize("@ss.hasPermi('labdata:employee:query')")
	@GetMapping(value = "/{orgKindId}/{employeeId}")
	public AjaxResult getInfo(@PathVariable("orgKindId") Long orgKindId, @PathVariable("employeeId") Long employeeId) {
		AjaxResult ajax = AjaxResult.success();
		List<SysRole> roles = orgKindRelRolesService.selectRoleListFromOrgKinds(orgKindId);
		ajax.put("roles", roles);
		//ajax.put("posts", postService.selectPostAll());
		if (StringUtils.isNotNull(employeeId) && employeeId > 0) {
			LabEmployee labEmployee = labEmployeeService.selectLabEmployeeById(employeeId);
			List<Long> roleIds  = labEmployeeRoleService.selectRolesByEmployeeId(employeeId);
			labEmployee.setRoleIds(new Long[roleIds.size()]);
			for(int i=0;i<roleIds.size();i++){
				labEmployee.getRoleIds()[i] = roleIds.get(i);
			}
			ajax.put(AjaxResult.DATA_TAG, labEmployee);
		}
		return ajax;
	}

	@GetMapping(value = "/loginInfo")
	public AjaxResult getInfo() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		Date now = new Date();
		LabHoliday day = labHolidayService.getLabHolidayByDate(sdf1.format(now));
		AjaxResult ajax = AjaxResult.success();
		Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
		SysUser sysUser = userService.selectUserById(userId);
		Map<String, String> loginMap = new HashMap<String, String>();
		loginMap.put("count", sysUser.getLoginNum() == null ? "1" : sysUser.getLoginNum() + "");
		loginMap.put("date", sdf.format(now));
		loginMap.put("name", sysUser.getNickName());
		loginMap.put("lastLogin", sysUser.getLastLoginTime() != null ? sdf2.format(sysUser.getLastLoginTime()) : "");
		loginMap.put("type", getWeek(now));
		if(day!=null){
			loginMap.put("isWork", day.getHolidayFlag().equals("1")?"工作日":"休息日");
		}else{
			loginMap.put("isWork", "日历未设");
		}
		ajax.put(AjaxResult.DATA_TAG, loginMap);
		return ajax;
	}

	private String getWeek(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		switch (dayOfWeek) {
		case 1:
			return "星期日";
		case 2:
			return "星期一";
		case 3:
			return "星期二";
		case 4:
			return "星期三";
		case 5:
			return "星期四";
		case 6:
			return "星期五";
		case 7:
			return "星期六";
		}
		return "";
	}

	/**
	 * 新增实验室工作人员
	 */
	@PreAuthorize("@ss.hasPermi('labdata:employee:edit')")
	@Log(title = "实验室工作人员", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody LabEmployee labEmployee) {
		if(labEmployee.getUserId()==null){
			labEmployee.setPassword(SecurityUtils.encryptPassword(labEmployee.getPassword()));
			if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(labEmployee.getUserName()))) {
				return AjaxResult.error("新增用户'" + labEmployee.getEmployeeNo() + "'失败，登录账号已存在");
			} else if (StringUtils.isNotEmpty(labEmployee.getPhonenumber()) &&UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(labEmployee))) {
				return AjaxResult.error("新增用户'" + labEmployee.getUserName() + "'失败，手机号码已存在");
			} else if (StringUtils.isNotEmpty(labEmployee.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(labEmployee))) {
				return AjaxResult.error("新增用户'" + labEmployee.getUserName() + "'失败，邮箱账号已存在");
			}
		}
		return toAjax(labEmployeeService.insertLabEmployee(labEmployee));
	}

	/**
	 * 修改实验室工作人员
	 */
	@PreAuthorize("@ss.hasPermi('labdata:employee:edit')")
	@Log(title = "实验室工作人员", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody LabEmployee labEmployee) {
		userService.checkUserAllowed(labEmployee);
		if (StringUtils.isNotEmpty(labEmployee.getPhonenumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(labEmployee))) {
			return AjaxResult.error("修改用户'" + labEmployee.getUserName() + "'失败，手机号码已存在");
		} else if (StringUtils.isNotEmpty(labEmployee.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(labEmployee))) {
			return AjaxResult.error("修改用户'" + labEmployee.getUserName() + "'失败，邮箱账号已存在");
		}
		return toAjax(labEmployeeService.updateLabEmployee(labEmployee));
	}

	/**
	 * 删除实验室工作人员
	 */
	@PreAuthorize("@ss.hasPermi('labdata:employee:edit')")
	@Log(title = "实验室工作人员", businessType = BusinessType.DELETE)
	@DeleteMapping("/{employeeId}")
	public AjaxResult remove(@PathVariable Long employeeId) {
		LabEmployee labEmployee = labEmployeeService.selectLabEmployeeById(employeeId);
		if(labEmployeeService.checkUserDelete(labEmployee)!=null){
			return AjaxResult.error("员工已经参与流程，不能删除!");
		}
		return toAjax(labEmployeeService.deleteLabEmployeeById(employeeId));
	}

	@GetMapping(value = "/search/{employeeNo}")
	public AjaxResult searchUserno(@PathVariable("employeeNo") String employeeNo) {
		return AjaxResult.success(labEmployeeService.queryEmployeeByName(employeeNo));
	}

	//获取当前登录人信息
	@GetMapping(value = "/getEmployeeInfo/{employeeNo}")
	public AjaxResult getEmployeeInfo(@PathVariable("employeeNo") String employeeNo) {
		List<LabEmployeeInfoDto> employeeInfo = labEmployeeService.getEmployeeInfo(employeeNo);
		LabReservation labReservation = new LabReservation();
		List<LabReservationParameterPersonnel> list = new ArrayList<>();
		if (employeeInfo.size() > 0){
			LabReservationParameterPersonnel labReservationParameterPersonnel = new LabReservationParameterPersonnel();
			labReservationParameterPersonnel.setApplicantNo(employeeInfo.get(0).getEmployeeNo());
			labReservationParameterPersonnel.setApplicantName(employeeInfo.get(0).getNickName());
			labReservationParameterPersonnel.setApplicantOrgId(employeeInfo.get(0).getDeptId());
			labReservationParameterPersonnel.setApplicantPhone(employeeInfo.get(0).getPhonenumber());
			labReservationParameterPersonnel.setApplicantId(employeeInfo.get(0).getEmployeeId());
			labReservationParameterPersonnel.setTitle(employeeInfo.get(0).getTitle());
			labReservationParameterPersonnel.setEmail(employeeInfo.get(0).getEmail());
			list.add(labReservationParameterPersonnel);
		}
		labReservation.setAppointmentList(list);
		return AjaxResult.success(labReservation);
	}
}
